package com.element.security.server.web;

import com.element.security.server.global.GlobalOAuth2RequestValidator;
import org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;

import javax.annotation.Resource;
import java.security.Principal;
import java.util.Map;

/**
 * @auther WuJun.Zhang
 * @date 2022/2/18 下午6:32
 */
@Controller
@SessionAttributes({"authorizationRequest", "org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint.ORIGINAL_AUTHORIZATION_REQUEST"})
public class AuthorizationController {

    @Resource
    private AuthorizationEndpoint authorizationEndpoint;

    @Resource
    private GlobalOAuth2RequestValidator globalOAuth2RequestValidator;

    @GetMapping(value = "oauth/authorize")
    public ModelAndView authorize(Map<String, Object> model,
                                  @RequestParam Map<String, String> parameters,
                                  SessionStatus sessionStatus, Principal principal) {
        authorizationEndpoint.setOAuth2RequestValidator(globalOAuth2RequestValidator);
        return authorizationEndpoint.authorize(model, parameters, sessionStatus, principal);
    }

    @PostMapping(value = {"oauth/authorize"}, params = {"user_oauth_approval"})
    public View approveOrDeny(@RequestParam Map<String, String> approvalParameters,
                              Map<String, ?> model,
                              SessionStatus sessionStatus, Principal principal) {
        return authorizationEndpoint.approveOrDeny(approvalParameters, model, sessionStatus, principal);
    }
}